package com.lagou.rpc.consumer.client.lb;

import org.apache.commons.lang3.RandomUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author xingyi
 */
public class LeastUseFirst extends BaseLoadBalanceStrategy {
    private ConcurrentHashMap<Integer, Integer> statistic = new ConcurrentHashMap<>();

    public LeastUseFirst() {
        for (int i = 0; i < clientSize; i++) {
            statistic.put(i, 0);
        }
    }

    @Override
    public int pickClientIndex() {
        int minIndex = 0;
        int minValue = statistic.get(minIndex);
        for (int i = 1; i < clientSize; i++) {
            final Integer counter = statistic.get(i);
            if (minValue > counter) {
                minValue = counter;
                minIndex = i;
            }
        }
        List<Integer> minIndexList = new ArrayList<>();
        for (int i = 0; i < clientSize; i++) {
            if (minValue == statistic.get(i)) {
                minIndexList.add(i);
            }
        }
        minIndex = minIndexList.get(RandomUtils.nextInt(0, minIndexList.size()));
        statistic.put(minIndex, statistic.get(minIndex) + 1);
        System.out.println(statistic);
        return minIndex;
    }

    @Override
    public void afterClientChanged() {
        statistic.put(clientSize - 1, 0);
    }
}
